package cn.org.timespace.easyframe.util.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 安全验证Filter，验证每一个请求，看用户是否登录，没有登录提示要进行登录 。
 * </p>
 * 
 * @version 1.0, 11/03/11
 * @since 1.0
 * @author 
 */

public class EfSecurityFilter implements Filter {
	
	private static final String NOT_LOGIN_PAGE = "/welcome.jsp";
	
	private List<String> notAuthPageList = new ArrayList<String>();
	
	private FilterConfig filterConfig;
	
	public void destroy() {
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		

		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		
		String uri = request.getRequestURI();
		String contextPath = request.getContextPath();
		String url = uri.substring(contextPath.length());
		
		if(!notAuthPageList.contains(url))
		{
			Object obj = request.getSession().getAttribute("efUserSession");
			if(obj == null){
				request.setAttribute("globalErrMsgToPage", "尊敬的用户，您好！你还没有登录本系统或者已有半小时未使用本系统，请重新登录！");
				response.sendRedirect(request.getContextPath() + NOT_LOGIN_PAGE);
			}
		}
		
		arg2.doFilter(arg0, arg1);
	}

	public void init(FilterConfig arg0) throws ServletException {
		this.filterConfig = arg0;
		
		notAuthPageList.add("/");
		notAuthPageList.add("/EnvCheck.jsp");
		notAuthPageList.add("/welcome.jsp");
		notAuthPageList.add("/efPreLogonAction.ef");
		notAuthPageList.add("/LogonForm.jsp");
		notAuthPageList.add("/efAuthCodeAction.ef");
		notAuthPageList.add("/efLogonAction.ef");
		notAuthPageList.add("/permission/systemMessageAction!doViewEfSystemHelp.ef");
		
	}

}
